import type * as AceLib from './ace.d.ts'

declare global {
  interface Window {
    ace?: typeof AceLib
  }
}

export type AceEditor = AceLib.Ace.Editor

export async function loadAce() {
  if (window.ace) return Promise.resolve()
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.src = 'https://cdn.jsdelivr.net/npm/ace-builds@1.22.0/src-min-noconflict/ace.min.js'
    document.body.appendChild(script)
    script.addEventListener('load', resolve)
    script.addEventListener('error', reject)
  })
}

export function initAceEditor(element: HTMLElement, initialValue: string): AceEditor | null {
  if (window.ace === undefined) return null
  const editor = window.ace.edit(element, {
    mode: 'ace/mode/html',
    selectionStyle: 'text',
    printMargin: false,
    wrap: true,
    tabSize: 2,
  })
  editor.session.setValue(initialValue)
  return editor
}
